#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "tusb.h"
#include "tinyusb.h"
#include "tinyusb_default_config.h"
#include "Bsp.h"
#include "comModuleUSB.h"
#include "usbd_iProfile.h"
#include "esp_log.h"
static const char *TAG = "USB_Device";
static bool usb_connected = false;

// USB设备描述符
static const tusb_desc_device_t device_descriptor = {
    .bLength = 0x12,                            /* bLength */
    .bDescriptorType = TUSB_DESC_DEVICE,        /* bDescriptorType */   
    .bcdUSB = 0x0200,                           /* bcdUSB */
    .bDeviceClass = 0x00,                       /* bDeviceClass */
    .bDeviceSubClass = 0x00,                    /* bDeviceSubClass */
    .bDeviceProtocol = 0x00,                    /* bDeviceProtocol */
    .bMaxPacketSize0 = CFG_TUD_ENDPOINT0_SIZE,  /* bMaxPacketSize0 */
    .idVendor = 0xD6A1,                         /* idVendor */
    .idProduct = 0x0011,                        /* idProduct */
    .bcdDevice = 0x0200,                        /* bcdDevice */
    .iManufacturer = 0x01,                      /* iManufacturer */
    .iProduct = 0x02,                           /* iProduct */
    .iSerialNumber = 0x03,                      /* iSerialNumber */
    .bNumConfigurations = 0x01                  /* bNumConfigurations */
};

// 配置描述符
static uint8_t const configuration_descriptor[] = {
    // 配置描述符
    0x09,                                   // bLength
    TUSB_DESC_CONFIGURATION,                // bDescriptorType
    USB_VCAM_CONFIG_DESC_SIZ, 0x00,         // wTotalLength
    0x01,                                   // bNumInterfaces
    0x01,                                   // bConfigurationValue
    0x00,                                   // iConfiguration
    0x80,                                   // bmAttributes
    150,                                    // MaxPower (150 * 2mA = 300mA)

    // 接口描述符
    0x09,                                   // bLength
    TUSB_DESC_INTERFACE,                    // bDescriptorType
    0x00,                                   // bInterfaceNumber
    0x00,                                   // bAlternateSetting
    0x03,                                   // bNumEndpoints
    0xFF,                                   // bInterfaceClass (Vendor Specific)
    TUSB_CLASS_VENDOR_SPECIFIC,             // bInterfaceSubClass
    0x00,                                   // bInterfaceProtocol
    0x00,                                   // iInterface

    // 端点3 - 批量IN
    0x07,                                   // bLength
    TUSB_DESC_ENDPOINT,                     // bDescriptorType
    USB_EP3_BULK_IN,                        // bEndpointAddress
    TUSB_XFER_BULK,                         // bmAttributes
    0x40, 0x00,                             // wMaxPacketSize
    0x00,                                   // bInterval

    // 端点1 - 中断IN
    0x07,                                   // bLength
    TUSB_DESC_ENDPOINT,                     // bDescriptorType
    USB_EP1_INT_IN,                         // bEndpointAddress
    TUSB_XFER_INTERRUPT,                    // bmAttributes
    0x40, 0x00,                             // wMaxPacketSize
    32,                                     // bInterval

    // 端点2 - 批量OUT
    0x07,                                   // bLength
    TUSB_DESC_ENDPOINT,                     // bDescriptorType
    USB_EP2_BULK_OUT,                       // bEndpointAddress
    TUSB_XFER_BULK,                         // bmAttributes
    0x40, 0x00,                             // wMaxPacketSize
    0x00                                    // bInterval


};

// 字符串描述符
static char const *string_descriptor[] = {
    (const char[]) { 0x09, 0x04 },         // 语言ID
    "VCAM",                                // 制造商
    "iProfile",                            // 产品名
    "12345678"                             // 序列号
};

// TinyUSB回调函数
void device_event_handler(tinyusb_event_t *event, void *arg)
{
    switch (event->id) {
    case TINYUSB_EVENT_ATTACHED:
        usb_connected = true;
        ESP_LOGI(TAG, "USB device attached to the Host");
        break;
    case TINYUSB_EVENT_DETACHED:
        usb_connected = false;
        break;
    default:
        break;
    }
}

//static uint16_t _desc_str[32];
//
///* TinyUSB 描述符回调 */
//uint8_t const *tud_descriptor_device_cb(void) {
//    return (uint8_t const *)&device_descriptor;
//}
//
//uint8_t const *tud_descriptor_configuration_cb(uint8_t index) {
//    return configuration_descriptor;
//}
//
//uint16_t const* tud_descriptor_string_cb(uint8_t index, uint16_t langid) {
//    (void)langid;
//    uint8_t chr_count;
//    
//    if (index == 0) {
//        memcpy(&_desc_str[1], string_descriptor[0], 2);
//        chr_count = 1;
//    } else {
//        if (index >= sizeof(string_descriptor)/sizeof(string_descriptor[0])) 
//            return NULL;
//        
//        const char* str = string_descriptor[index];
//        chr_count = strlen(str);
//        if (chr_count > 31) chr_count = 31;
//        
//        for (uint8_t i = 0; i < chr_count; i++) {
//            _desc_str[1 + i] = str[i];
//        }
//    }
//    
//    _desc_str[0] = (TUSB_DESC_STRING << 8) | (2 * chr_count + 2);
//    return _desc_str;
//}

/* 端点1中断传输 */
void send_interrupt_data(void) {
    if (usb_connected) {
        // 准备中断数据
        // tud_vendor_n_write(USB_EP1_INT_IN, comModule_int_Buf, 8);
    }
}

/* 端点2批量OUT接收 */
void tud_vendor_rx_cb(uint8_t itf, uint8_t const* buffer, uint16_t bufsize){
    if (bufsize > 0 && bufsize <= sizeof(comModule_Buf)) {
        memcpy(comModule_Buf, buffer, bufsize);
        usb_trans_length = bufsize;

        // 释放信号量通知数据到达
        if (sem_usb_com != NULL) {
            xSemaphoreGive(sem_usb_com);
            // ESP_LOGI(TAG, "Semaphore given to notify data arrival");
        }
    }
}

/* 端点3批量IN传输 */
esp_err_t USB_Trans_CmdBuf(uint8_t *pBuf,uint8_t length) {
    uint32_t ret = 65;

    tud_vendor_read_flush();
    // 使用Vendor类API发送批量数据
    ret = tud_vendor_write(pBuf, length);

    ret = tud_vendor_write_flush();
    
    return ESP_OK;
}

// 初始化USB设备
void usb_port_init(void)
{
    // TinyUSB配置
    tinyusb_config_t tusb_cfg = TINYUSB_DEFAULT_CONFIG(device_event_handler);
    tusb_cfg.descriptor.device = &device_descriptor;                  // 设备描述符
    tusb_cfg.descriptor.full_speed_config = configuration_descriptor; // 全速配置描述符
    tusb_cfg.descriptor.string = string_descriptor;               // 字符串描述符数组
    tusb_cfg.descriptor.string_count = sizeof(string_descriptor) / sizeof(string_descriptor[0]);
    tusb_cfg.phy.skip_setup = false;
 
    ESP_ERROR_CHECK(tinyusb_driver_install(&tusb_cfg));   
    
    // 启动中断传输
    // tud_ready();
}

